<template>
  <!-- ! 页面内展示微应用 -->
  <div class="micro-apps">
    <div :id="appRef" style="width: 100%; height: 100%"></div>
  </div>
</template>
<script>
import {
  defineComponent,
  onMounted,
  onBeforeUnmount,
  reactive,
  toRefs,
  watch,
  nextTick,
} from "vue";
import utils from "../../common/utils/utils";
// import { innerPageLoadApp, MICRO_APPS } from "../../micro_apps/index";
export default defineComponent({
  name: "PageInnerMicroApps",
  props: {
    // 调起的页面标识
    pageFrom: {
      type: String,
      default: "",
    },
    // 启动的应用
    microName: {
      type: String,
      default: "",
    },
    // 启动页面 pathName?param1=1&param2=2
    loadPage: {
      type: String,
      default: "",
    },
    // 子应用需要渲染的组件文件名
    component: {
      type: String,
      default: "",
    },
    // 展示当前应用
    show: {
      type: Boolean,
      default: false,
    },
    // 打开的微应用页面内需要展示的组件（抽屉，modal等)
    showComponent: {
      type: String,
      default: "",
    },
  },
  setup(props, { emit }) {
    const state = reactive({
      // 加载的app
      app: null,
      appParams: {},
      // 挂载的app的div id
      appRef: null,
    });
    const loadMicroApp = () => {
      if (state.app) {
        return;
      }
      // todo...
      // const currentApp = MICRO_APPS.find(
      //   (item) => item.name == props.microName
      // );
      // state.app = innerPageLoadApp({
      //   loadInfo: {
      //     name: state.appRef,
      //     entry: currentApp.entry,
      //     container: `#${state.appRef}`,
      //   },
      //   propsInfo: {
      //     containerPage: location.hash.split("#")[1],
      //     ...state.appParams,
      //   },
      // });
    };

    onMounted(() => {
      if (props.show) {
        loadMicroApp();
      }
    });

    onBeforeUnmount(() => {
      if (state.app) {
        state.app.unmount();
      }
    });

    const init = () => {
      if (!props.show) {
        return;
      }
      state.appParams = {};
      const paramsArr = props.loadPage.split("?");
      state.appParams.currentPathName = paramsArr[0];
      state.appParams.component =
        props.component || state.appParams.currentPathName;
      if (paramsArr[1]) {
        state.appParams.currentParams = utils.getQueryObj(paramsArr[1]);
      }
      state.appRef = `${props.pageFrom}_${props.microName}_${state.appParams.currentPathName}`;
      if (props.showComponent) {
        state.appParams.showComponent = props.showComponent;
      }
    };

    init();
    watch(
      () => props.show,
      (show) => {
        if (show) {
          init();
          nextTick(() => {
            loadMicroApp();
          });
        }
      }
    );
    return {
      ...toRefs(state),
    };
  },
});
</script>
<style scoped>
.micro-apps {
  width: 100%;
  height: 100%;
  position: relative;
}
</style>
